package com.zkjd.lingdong.ui.led

import android.widget.Toast
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavController
import com.zkjd.lingdong.model.LedColor
import kotlin.math.roundToInt

@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun LedColorScreen(
    navController: NavController,
    viewModel: LedColorViewModel = hiltViewModel(),
    deviceMac: String
) {
    val connectedColor by viewModel.connectedLedColor.collectAsState()
    val reconnectingColor by viewModel.reconnectingLedColor.collectAsState()
    val isConnectedMode by viewModel.isConnectedMode.collectAsState()
    val presetColors = viewModel.presetColors
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    var toast: Toast? = null
    val context = LocalContext.current
    // 根据当前选择的模式，确定当前显示的颜色
    val currentColor = if (isConnectedMode) connectedColor else reconnectingColor
    
    // 当前选中的颜色，用HSV模式表示
    var currentHue by remember { mutableFloatStateOf(0f) }
    
    // 当当前颜色变化时更新HSV值
    LaunchedEffect(currentColor) {
        // 转换Color为HSV，提取色相值
        val hsv = FloatArray(3)
        android.graphics.Color.colorToHSV(currentColor.color.toArgb(), hsv)
        currentHue = hsv[0]
    }
    
    // 加载设备颜色
    LaunchedEffect(key1 = deviceMac) {
        //设置
        viewModel.setColorMode(true)
        viewModel.loadDeviceColor(deviceMac)
    }
    
    // 监听UI事件
    LaunchedEffect(key1 = true) {
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.uiEvents.collect { event ->
                when (event) {
                    is LedColorViewModel.UiEvent.ShowError -> {
                        if(toast==null) {
                            toast = Toast.makeText(context, event.message, Toast.LENGTH_SHORT)
                        }else{
                            //有新的消息即时更新，不用等待上一个消息显示完成以后再显示，造成延时很长的感觉
                            toast?.setText(event.message)
                        }
                        toast?.show()
                    }
                    is LedColorViewModel.UiEvent.ColorApplied -> {
                        // 颜色应用成功，返回上一页
                        navController.popBackStack()
                    }
                }
            }
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("LED灯颜色设置") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF1C1C28),//MaterialTheme.colorScheme.primary,
                    titleContentColor = Color(0xFFFFFFFF),//MaterialTheme.colorScheme.onPrimary
                ),
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回",
                            tint = MaterialTheme.colorScheme.onPrimary
                        )
                    }
                }
            )
        },
        containerColor = Color(0xFF1C1C28)
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 颜色模式选择
//            ColorModeSelector(
//                isConnectedMode = isConnectedMode,
//                onModeChanged = { viewModel.setColorMode(it) }
//            )

            Spacer(modifier = Modifier.height(16.dp))
            
            // 颜色预览
            val displayColor = Color.hsv(currentHue, 1f, 1f)
            ColorPreview(
                color = displayColor,
                //title = if (isConnectedMode) "工作模式颜色预览" else "回连模式颜色预览"
                title = "颜色预览"
            )
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 预设颜色选择
            Text(
                text = "预设颜色",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 8.dp),
                color = Color.White
            )
            
            FlowRow(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
                maxItemsInEachRow = 4
            ) {
                presetColors.forEach { color ->
                    PresetColorItem(
                        color = color,
                        isSelected = color.color.toArgb() == displayColor.toArgb(),
                        onClick = { 
                            viewModel.selectPresetColor(color)
                            // 更新当前HSV值
                            val hsv = FloatArray(3)
                            android.graphics.Color.colorToHSV(color.color.toArgb(), hsv)
                            currentHue = hsv[0]
                        }
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 自定义颜色选择器
            Text(
                text = "自定义颜色",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 8.dp),
                color = Color.White
            )
            
            // 颜色选择器
            ColorPickerBar(
                hue = currentHue,
                onHueChanged = { hue ->
                    currentHue = hue
                    val newColor = Color.hsv(hue, 1f, 1f)
                    viewModel.selectCustomColor(newColor, "自定义")
                }
            )
            
            Spacer(modifier = Modifier.weight(1f))
            
            // 操作按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Button(
                    onClick = { navController.popBackStack() },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF3C3C4A),
                        contentColor = Color.White
                    ),
                    shape = RoundedCornerShape(8.dp),
                    modifier = Modifier.weight(1f)
                ) {
                    Text("取消")
                }
                
                Spacer(modifier = Modifier.width(16.dp))
                
                Button(
                    onClick = { viewModel.applyColorSetting() },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    ),
                    shape = RoundedCornerShape(8.dp),
                    modifier = Modifier.weight(1f)
                ) {
                    Text("应用")
                }
            }
        }
    }
}

//全色系 序把里面全部100改成361
@Composable
fun ColorPickerBar(
    hue: Float,
    onHueChanged: (Float) -> Unit
) {
    val colors = List(361) { i -> Color.hsv(i.toFloat(), 1f, 1f) }
    val gradientBrush = remember {
        Brush.horizontalGradient(colors)
    }
    
    val density = LocalDensity.current
    val barHeight = 40.dp
    val thumbWidth = 4.dp
    val thumbWidthPx = with(density) { thumbWidth.toPx() }
    
    var isDragging by remember { mutableStateOf(false) }
    var barWidth by remember { mutableStateOf(0f) }
    var thumbPosition by remember { mutableFloatStateOf(0f) }
    
    // 根据hue更新滑块位置
    LaunchedEffect(hue, barWidth) {
        if (barWidth > 0) {
            thumbPosition = hue / 360f * barWidth
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(barHeight)
            .padding(horizontal = thumbWidth)
    ) {
        // 颜色条
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(barHeight)
                .clip(RoundedCornerShape(barHeight / 2))
                .background(gradientBrush)
                .onSizeChanged { size -> 
                    barWidth = size.width.toFloat()
                    thumbPosition = hue / 360f * barWidth
                }
                .pointerInput(Unit) {
                    detectDragGestures { change, dragAmount ->
                        change.consume()
                        val newX = (thumbPosition + dragAmount.x).coerceIn(0f, barWidth)
                        thumbPosition = newX
                        val newHue = (thumbPosition / barWidth) * 360f
                        onHueChanged(newHue)
                    }
                }
        )
        
        // 颜色条点击事件
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(barHeight)
                .clip(RoundedCornerShape(barHeight / 2))
                .pointerInput(Unit) {
                    detectDragGestures(
                        onDragStart = { offset ->
                            isDragging = true
                            // 直接更新位置到点击位置
                            thumbPosition = offset.x.coerceIn(0f, barWidth)
                            val newHue = (thumbPosition / barWidth) * 360f
                            onHueChanged(newHue)
                        },
                        onDragEnd = { isDragging = false },
                        onDragCancel = { isDragging = false },
                        onDrag = { change, dragAmount ->
                            change.consume()
                            val newX = (thumbPosition + dragAmount.x).coerceIn(0f, barWidth)
                            thumbPosition = newX
                            val newHue = (thumbPosition / barWidth) * 360f
                            onHueChanged(newHue)
                        }
                    )
                }
        )
        
        // 滑块 - 改为竖条
        Box(
            modifier = Modifier
                .width(thumbWidth)
                .height(barHeight)
                .offset { IntOffset(thumbPosition.roundToInt() - thumbWidthPx.roundToInt() / 2, 0) }
                .shadow(4.dp, RoundedCornerShape(thumbWidth / 2))
                .background(Color.White, RoundedCornerShape(thumbWidth / 2))
                .border(1.dp, Color.hsv(hue, 1f, 1f), RoundedCornerShape(thumbWidth / 2))
        )
    }
}

@Composable
fun ColorModeSelector(
    isConnectedMode: Boolean,
    onModeChanged: (Boolean) -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF2D2D3A)
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "颜色模式",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                color = Color.White
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .selectableGroup(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    modifier = Modifier
                        .weight(1f)
                        .selectable(
                            selected = isConnectedMode,
                            onClick = { onModeChanged(true) },
                            role = Role.RadioButton
                        )
                        .padding(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    RadioButton(
                        selected = isConnectedMode,
                        onClick = null
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "工作模式",
                        fontSize = 14.sp,
                        color = Color.White
                    )
                }
                
                Row(
                    modifier = Modifier
                        .weight(1f)
                        .selectable(
                            selected = !isConnectedMode,
                            onClick = { onModeChanged(false) },
                            role = Role.RadioButton
                        )
                        .padding(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    RadioButton(
                        selected = !isConnectedMode,
                        onClick = null
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "回连模式",
                        fontSize = 14.sp,
                        color = Color.White
                    )
                }
            }
        }
    }
}

@Composable
fun ColorPreview(
    color: Color,
    title: String
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            color = Color.White
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Surface(
            modifier = Modifier
                .size(120.dp)
                .shadow(4.dp, CircleShape),
            shape = CircleShape,
            color = color
        ) {
            // 空内容，只用于显示颜色
        }
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Text(
            text = "#${String.format("%02X", (color.red * 255).toInt())}${String.format("%02X", (color.green * 255).toInt())}${String.format("%02X", (color.blue * 255).toInt())}",
            color = Color.White,
            fontSize = 14.sp
        )
    }
}

@Composable
fun PresetColorItem(
    color: LedColor,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .size(width = 70.dp, height = 40.dp)
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(8.dp),
        border = if (isSelected) BorderStroke(2.dp, Color.White) else null,
        colors = CardDefaults.cardColors(
            containerColor = color.color
        )
    ) {
        // 卡片内容为空，只显示颜色
    }
} 